package com.example.springboot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.example.springboot.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {

    @Value("${server.port}")
    private String port;

    private static final String ip = "http://localhost";


    /**
     * 上传接口
     */
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //获取源文件的名称包含文件名字和类型
        // 定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID(); // 生成不同的字符串
        //"user.dir")表示获取主路径D:/NewHormonyosshuju/SpringbootVue/vue
        String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/" + flag + '_' + originalFilename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);// 把文件写入到上传的路径
        return Result.success(ip + ":" + port + "/files/" + flag + '_' + originalFilename); // 返回结果 url

    }

    /**
     * 下载接口
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) { // HttpServletResponse通过数据流的方式把当前的文件发送到服务器
        OutputStream os; // 新建一个输出流对象

        String basePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/"; // 定义文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse(""); // 获取跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName); // 通过文件的路径读取文件字节流
                os = response.getOutputStream(); // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();

            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {


        @Value("${file.custom}")
        private Boolean isCustom;
        @Value("${file.staticAccessPath}")
        private String staticAccessPath;
        @Value("${file.uploadFolder}")
        private String uploadFolder;
        // 静态资源展示
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // PS：注意文件路径最后的斜杠（文件分隔符），如果缺少了，就不能够正确的映射到相应的目录
            String path = this.getClass().getClassLoader().getResource("application.yml").getPath();
            String dir = path.substring(0, path.lastIndexOf("/"));
            System.out.println("ftf ----> " +dir);
            System.out.println("-->" +path);
            String newUploadDir = dir + "files";
            if (isCustom){
                registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
            }else {
//                String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/";
//                registry.addResourceHandler(rootFilePath);

                registry.addResourceHandler(staticAccessPath).addResourceLocations(newUploadDir);
            }

        }

    }


}
